/*
 * @Author: zhang zhijiang 2824735304@qq.com
 * @Date: 2025-04-24 16:41:42
 * @LastEditors: zhang zhijiang 2824735304@qq.com
 * @LastEditTime: 2025-04-26 15:45:35
 * @FilePath: /linux/tcpcalculator/tcpserver.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once
#include <iostream>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include"sock.hpp"
#include<functional>
#include"protocol.hpp"
#include<signal.h>
using func_t = std::function<std::string(std::string& package)>;
class tcpserver
{
public:
    tcpserver(uint16_t port,func_t callback):_port(port),_callback(callback)
    {
    }
    ~tcpserver()
    {
    }
    void init()
    {
        listensock_.Init();
        listensock_.Bind(_port);
        listensock_.Listen();
    }
    void start()
    {
        signal(SIGCHLD,SIG_IGN);//不用等待子进程
        while(true)
        {
            std::string clientip;
            uint16_t clientport;
            
            int sockfd = listensock_.Accept(clientip,clientport);
            
            if (sockfd<0)
                continue;
            if(fork()==0) 
            {
                std::string inbuffer_stream;
                listensock_.Close();
                while (true)
                {
                        char inbuffer[128];
                        ssize_t n = read(sockfd,inbuffer,sizeof(inbuffer));
                        
                        if(n>0)
                        {         
                            inbuffer[n] = 0;
                            inbuffer_stream +=inbuffer;
                            cout<<inbuffer_stream<<endl;
                            std::string info = _callback(inbuffer_stream);
                            if(info.empty()) continue;
                            write(sockfd,info.c_str(),info.size());//这儿也是
                        }

                    if(n<=0)break;
                }
                exit(0);
            }
            close(sockfd);
        }
    }

private:
    sock listensock_;
    uint16_t _port;
    func_t _callback;
};